// pages/index/index.js
const app = getApp();
const auth = require('../../utils/clientAuth');
const scanner = require('../../utils/scanner');

Page({
  data: {
    isLoggedIn: false,
    userInfo: null,
    accounts: []
  },

  onLoad() {
    this.checkLoginStatus();
  },

  async onShow() {
    // 检查本地token是否存在
    const token = auth.getToken();
    if (!token) {
      wx.redirectTo({
        url: '/pages/verification/verification'
      });
      return;
    }

    // 验证token
    try {
      const validationResult = await auth.validateToken();
      if (!validationResult.valid) {
        wx.redirectTo({
          url: '/pages/verification/verification'
        });
        return;
      }

      // token有效，获取账号列表
      await this.fetchAccounts();
    } catch (err) {
      wx.redirectTo({
        url: '/pages/verification/verification'
      });
    }
  },

  // 检查登录状态
  checkLoginStatus() {
    if(app.globalData.isLoggedIn){
      this.setData({
      isLoggedIn
    });
  }

  if(!app.globalData.isLoggedIn){
      wx.redirectTo({
        url: '/pages/verification/verification'
      });
    }
  },

  // 获取账号列表
  async fetchAccounts() {
    try {
      app.showLoading('加载账号列表...');
      const accounts = await auth.getAvailableAccounts();
      this.setData({
        accounts,
        isLoggedIn: true
      });
    } catch (err) {
      app.showError('获取账号列表失败');
    } finally {
      app.hideLoading();
    }
  },

  // 扫码登录
  async handleScan() {
    try {
      const scanResult = await scanner.scanCode();
      const sceneInfo = await scanner.getSceneInfo(scanResult.scene);
      await scanner.updateScanStatus(scanResult.scene, 'SCANNED');
      
      wx.navigateTo({
        url: `/pages/account/account?scene=${scanResult.scene}&appId=${scanResult.appId}`
      });
    } catch (err) {
      if (err.message !== '用户取消扫码') {
        app.showError(err.message || '扫码失败');
      }
    }
  },

  // 退出登录
  async handleLogout() {
    try {
      app.showLoading('退出登录...');
      await auth.logout();
      wx.redirectTo({
        url: '/pages/verification/verification'
      });
    } catch (err) {
      app.showError('退出失败');
    } finally {
      app.hideLoading();
    }
  }
});
